package demo.main;

import static net.sf.dynamicreports.report.builder.DynamicReports.col;
import static net.sf.dynamicreports.report.builder.DynamicReports.field;
import static net.sf.dynamicreports.report.builder.DynamicReports.report;
import static net.sf.dynamicreports.report.builder.DynamicReports.type;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.dynamicreports.report.builder.FieldBuilder;
import net.sf.dynamicreports.report.builder.column.PercentageColumnBuilder;
import net.sf.dynamicreports.report.builder.column.TextColumnBuilder;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;

import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

public class PercentageColumns extends MutiReport {
	private FieldBuilder<BigDecimal> unitPriceField;

	@At("/getPercentageColumn")
	@Ok("json")
	public String getPercentageColumns(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("getPercentageColumns");
		build(request, response);
		return resultResult;
	}
	
	@Override
	protected void build(HttpServletRequest request, HttpServletResponse response) {
		try {
			unitPriceField = field("unitprice", BigDecimal.class);
			
			TextColumnBuilder<String>  itemColumn          = col.column("产品", "item", type.stringType());
			TextColumnBuilder<Integer> quantityColumn      = col.column("数量", "quantity", type.integerType());
			PercentageColumnBuilder    quantityPercColumn  = col.percentageColumn("数量 [%]", quantityColumn);
			PercentageColumnBuilder    unitPricePercColumn = col.percentageColumn("单价 [%]", unitPriceField);
			
			reportBuilder = report()
			  .setTemplate(Templates.reportTemplate)
			  .fields(
			  	unitPriceField)
			  .columns(
			  	itemColumn, quantityColumn, quantityPercColumn, unitPricePercColumn)
			  .title(Templates.createTitleComponent(""))
			  .pageFooter(Templates.footerComponent)
			  .setDataSource(createDataSource());
			setResult(reportBuilder.toJasperPrint(), request, response);
		} catch (DRException e) {
			e.printStackTrace();
		}
	}

	private JRDataSource createDataSource() {
		DataSource dataSource = new DataSource("item", "quantity", "unitprice");
		dataSource.add("图书", 3, new BigDecimal(11));
		dataSource.add("图书", 1, new BigDecimal(15));
		dataSource.add("图书", 5, new BigDecimal(10));
		dataSource.add("图书", 8, new BigDecimal(9));
		return dataSource;
	}
}
